package com.ubb.dbms.core.fileManagers.indexFileManager.bPlusTree;
import com.ubb.dbms.core.fileManagers.indexFileManager.IndexFileIO;
import com.ubb.dbms.core.fileManagers.indexFileManager.IndexFileManager;

public class Node {
	private static final int T = IndexFileManager.T;
	private int mNumKeys = 0;
	private int[] mKeys = new int[2 * T - 1];
	private Object[] mObjects = new Object[2 * T - 1];
	private int[] mChildNodePointers = new int[2 * T]; // Node pointers (rowNr)
	private boolean mIsLeafNode;
	private int mNextNodePointer; // Node pointer (rowNr)
	private int rowNr;
	
	private IndexFileIO indexFileIO;

	public Node(IndexFileIO indexFileIO) {
		this.indexFileIO = indexFileIO;
	}

	public int getmNumKeys() {
		return mNumKeys;
	}

	public void setmNumKeys(int mNumKeys) {
		this.mNumKeys = mNumKeys;
	}

	public int[] getmKeys() {
		return mKeys;
	}

	public void setmKeys(int[] mKeys) {
		this.mKeys = mKeys;
	}
	
	public void setmKey(int key, int index){
		this.mKeys[index] = key;
	}

	public Object[] getmObjects() {
		return mObjects;
	}
	
	public Object getmObject(int index) {
		return this.mObjects[index];
	}

	public void setmObjects(Object[] mObjects) {
		this.mObjects = mObjects;
	}
	
	public void setmObject(Object object, int index){
		this.mObjects[index] = object;
	}
	
	public Node getmChildNode(int mChildIndex) {
		int childNodeRowNr = this.mChildNodePointers[mChildIndex];
		Node childNode = indexFileIO.readRow(childNodeRowNr);
		return childNode;
	}
	
	public int getmChildNodeOffset(int mChildIndex) {
		return mChildNodePointers[mChildIndex];
	}

	public void setmChildNode(int mChildNodePointer, int index) {
		this.mChildNodePointers[index] = mChildNodePointer;
	}

	public boolean ismIsLeafNode() {
		return mIsLeafNode;
	}

	public void setmIsLeafNode(boolean mIsLeafNode) {
		this.mIsLeafNode = mIsLeafNode;
	}

	public Node getmNextNode() {
		if (mNextNodePointer == 0) {
			return null;
		}
		return getmChildNode(this.mNextNodePointer);
	}
	
	public int getmNextNodeOffset() {
		return this.mNextNodePointer;
	}

	public void setmNextNode(int mNextNodePointer) {
		this.mNextNodePointer = mNextNodePointer;
	}
	
	public int getRowNr() {
		return rowNr;
	}

	public void setRowNr(int rowNr) {
		this.rowNr = rowNr;
	}

	public int getmNumKey(int index) {
		return this.mKeys[index];
	}

	public void setIndexFileIO(IndexFileIO indexFileIO) {
		this.indexFileIO = indexFileIO;
	}

	public void updateHeaderInFileForNode(){
		indexFileIO.updateHeader(this.getRowNr());
	}
	
	public void updateNodeInFile() {
		if (rowNr == 0) {
			rowNr = indexFileIO.insertRow(this);
		} else {
			indexFileIO.updateRow(this, rowNr);
		}
	}
}
